<?php


namespace services\base;


use common\helpers\DateHelper;
use common\models\buss\CommonRelation;
use common\models\member\Member;
use services\log\LogMemberOpService;
use Yii;
use yii\web\HttpException;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\base\Tags;

class TagsService extends Service
{
    /**
     * 标签列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function tagsList(array $params, int $page, int $pageSize): array
    {
        $query = Tags::find()
            ->where([
                'status' => [
                    Tags::STATUS_ENABLE,
                    Tags::STATUS_INVALID
                ],
            ]);
        if (isset($params['keywords']) && $params['keywords']) {
            $query->andWhere(['like', 'name', $params['keywords']]);
        }
        if (isset($params['type']) && $params['type']) {
            $query->andWhere(['type' => $params['type']]);
        }

        $orderBy = [];
        if (isset($params['order_column']) && $params['order_column']) {
            $sort = isset($params['order_sort']) && $params['order_sort'] == 'asc' ? SORT_ASC : SORT_DESC;
            switch ($params['order_column']) {
                case 'updated_at':
                    $orderBy['updated_at'] = $sort;
                    break;
                case 'created_at':
                    $orderBy['created_at'] = $sort;
                    break;
                default :
                    break;
            }
        }
        $orderBy['status'] = SORT_DESC;
        $orderBy['sort'] = SORT_ASC;
        $orderBy['id'] = SORT_DESC;
        $list = $this->getListPageRes($query, $page, $pageSize, $orderBy);
        foreach ($list['list'] as &$val) {
            $val['type_name'] = Tags::$types[$val['type']];
            $memberInfo = Member::findOne(['id' => $val['created_member_id']]);
            $val['created_member_name'] = $memberInfo ? $memberInfo->realname : '';
            $val['created_at_str'] = DateHelper::timestampToDate($val['created_at']);
            $val['updated_at_str'] = DateHelper::timestampToDate($val['updated_at']);
        }
        return $list;
    }

    /**
     * 获取正常
     * @param int $type
     * @param array|int|null $ids
     * @return Tags[]
     */
    public static function getEnableListByIds(int $type, $ids = null): array
    {
        $query = Tags::find()
            ->select(['*'])
            ->where([
                'type' => $type,
                'status' => Tags::STATUS_ENABLE,
            ]);
        if (!is_null($ids)) {
            $query->orWhere([
                'id' => $ids,
                'status' => [Tags::STATUS_INVALID, Tags::STATUS_ENABLE],
            ]);
        }
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all();
    }

    /**
     * 详情绑定标签列表
     * @param int $type
     * @param int|array|null $ids
     * @return array
     */
    public static function getEditCondition(int $type, $ids = null): array
    {
        return CommonHelper::getListCondition(self::getEnableListByIds($type, $ids), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 根据Ids获取标签列表【禁用 + 正常】
     * @param int $type
     * @param array|null $ids
     * @return Tags[]
     */
    public static function getNormalListByIds(int $type, ?array $ids = null): array
    {
        $query = Tags::find()
            ->select(['*'])
            ->where([
                'type' => $type,
                'status' => [Tags::STATUS_INVALID, Tags::STATUS_ENABLE],
            ]);
        if (is_array($ids)) {
            $query->andWhere(['id' => $ids]);
        }
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all();
    }

    /**
     * 获取下拉列表筛选项
     * @return array
     */
    public static function getListCondition(int $type): array
    {
        return CommonHelper::getListCondition(self::getNormalListByIds($type), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 根据名称获取标签列表
     * @param int $type
     * @param string|array $names
     * @return Tags[]
     */
    public static function getNormalListByName(int $type, $names): array
    {
        return Tags::findAll([
            'type' => $type,
            'name' => $names,
            'status' => [Tags::STATUS_ENABLE, Tags::STATUS_INVALID]
        ]);
    }

    /**
     * 根据名称获取正常标签列表
     * @param int $type
     * @param string|array $names
     * @return Tags[]
     */
    public static function getEnableListByName(int $type, $names): array
    {
        return Tags::findAll([
            'type' => $type,
            'name' => $names,
            'status' => Tags::STATUS_ENABLE
        ]);
    }

    /**
     * 根据名称获取禁用标签列表
     * @param int $type
     * @param string|array $names
     * @return Tags[]
     */
    public static function getInvalidListByName(int $type, $names): array
    {
        return Tags::findAll([
            'type' => $type,
            'name' => $names,
            'status' => Tags::STATUS_INVALID
        ]);
    }

    /**
     * 更新标签
     */
    public function updateTags(array $params)
    {
        $check = Tags::find()
            ->select(['id'])
            ->where([
                'and',
                ['!=', 'id', $params['id']],
                ['name' => $params['name']],
                ['type' => $params['type']],
                ['status' => [Tags::STATUS_ENABLE, Tags::STATUS_INVALID]]
            ])->asArray()->one();
        if ($check) {
            return CommonHelper::api(422, '当前类型下，该标签名称已存在');
        }
        $oldTags = self::getData($params['id']);
        $tags = Tags::findOne(['id' => $params['id']]);
        $tags->name = $params['name'];
        $tags->type = $params['type'];
        $tags->sort = $params['sort'] ?? 100;
        $tags->status = $params['status'] ?? Tags::STATUS_ENABLE;
        $tags->operation_id = Yii::$app->user->identity->member_id;
        $tags->operation_name = Yii::$app->user->identity->member->realname;
        $tags->saveAndCheckResult();
        // 添加日志
        LogMemberOpService::createTagsLog('edit', $tags, $oldTags);
        return $tags->id;
    }

    /**
     * 新增标签
     * @throws \Exception
     */
    public function createTags($params): int
    {
        $tagsArr = array_unique(explode(',', CommonHelper::strFormat($params['name'])));
        $addList = [];
        foreach ($tagsArr as $val) {
            $checkRet = Tags::findOne(['name' => $val, 'type' => $params['type'], 'status' => [Tags::STATUS_ENABLE, Tags::STATUS_INVALID]]);
            if ($checkRet) {
                throw new \Exception('当前类型下，标签:' . $checkRet->name . '已存在');
            }

            $add['name'] = $val;
            $add['type'] = $params['type'];
            $add['sort'] = $params['sort'] ?? 100;
            $add['created_member_id'] = Yii::$app->user->identity->member_id;
            $add['operation_id'] = Yii::$app->user->identity->member_id;
            $add['operation_name'] = Yii::$app->user->identity->member->realname;
            $add['created_at'] = time();
            $add['updated_at'] = time();
            $addList[] = $add;
        }
        $res = Yii::$app->db->createCommand()
            ->batchInsert(Tags::tableName(),
                ['name', 'type', 'sort', 'created_member_id', 'operation_id', 'operation_name', 'created_at', 'updated_at'],
                $addList)
            ->execute();

        // 添加日志
        $new = new Tags();
        $new->id = 0;
        $new->name = $params['name'];
        $new->type = $params['type'];
        LogMemberOpService::createTagsLog('create', $new);
        return $res;
    }

    /**
     * 标签数据
     * @param int $id
     * @return Tags|null
     */
    public static function getData(int $id): ?Tags
    {
        return Tags::findOne($id);
    }

    /**
     * 标签删除
     */
    public function deleteTags(array $params): array
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 删除标签
            Tags::updateAll([
                'status' => Tags::STATUS_DELETE,
                'operation_id' => Yii::$app->user->identity->member_id,
                'operation_name' => Yii::$app->user->identity->member->realname,
                'updated_at' => time()
            ], ['id' => $params['id']]);

            // 内容标签解绑
            CommonRelationService::unbindByRelationId(CommonRelation::TYPE_CONTENT, $params['id']);

            // 工具导航标签解绑
            CommonRelationService::unbindByRelationId(CommonRelation::TYPE_TOOL_TAG, $params['id']);

            $transaction->commit();
            // 添加日志
            LogMemberOpService::createTagsLog('delete', self::getData($params['id']));

            return ['id' => $params['id']];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}
